package com.xzm.project.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.orhanobut.logger.Logger;
import com.xzm.project.R;

import cn.wuyu.baselibrary.utils.ResUtils;
import cn.wuyu.baselibrary.utils.ToastUtil;

/**
 * author : xuzongmeng
 * date   : 2019/9/2
 * desc   : 参考 https://blog.csdn.net/harvic880925/article/details/38926877
 */
public class MyCanvas extends View {
    private int defaultSize;
    private Paint mPaint;
    private Canvas mCanvas;

    public MyCanvas(Context context) {
        this(context, null);
    }

    //
    public MyCanvas(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public MyCanvas(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initMyView();
    }

    private void initMyView() {
        //initHandler();
        initPaint();
//       initAttr(context, attrs);
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setColor(ResUtils.getColor(R.color.Red));
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(5);
        mPaint.setAntiAlias(true);
//        mPaint.setShadowLayer(10, 15, 12, Color.GREEN);
    }

    private void initAttr(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        defaultSize = typedArray.getDimensionPixelSize(R.styleable.MyView_default_size, 100);
        typedArray.recycle();
        initPaint();
    }
    /*----------------------------layout布局----------------------------*/
//    @Override
//    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
////        int width = getMySize(100, widthMeasureSpec);
////        int height = getMySize(100, heightMeasureSpec);
////        setMeasuredDimension(width, height);
//    }
////
//    private int getMySize(int defaultSize, int measureSpec) {
//        int mySize = defaultSize;
//        int mode = MeasureSpec.getMode(measureSpec);
//        int size = MeasureSpec.getSize(defaultSize);
//        switch (mode) {
//            case MeasureSpec.UNSPECIFIED:
//                mySize = defaultSize;
//                break;
//            case MeasureSpec.AT_MOST: //如果测量模式是最大取值为size
//                //我们将大小取最大值,你也可以取其他值
//                mySize = size;
//                break;
//            case MeasureSpec.EXACTLY: //如果是固定的大小，那就不要去改变它
//                mySize = size;
//                break;
//        }
//        return mySize;
//    }

//
//    @Override
//    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
//        super.onLayout(changed, left, top, right, bottom);
//    }

    /*----------------------------Drawing绘制----------------------------*/
    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        mCanvas = canvas;
//        drawLine();
//        drawLines();
//        drawPoint();
//        drawPoints();
//          drawCircle();
//        drawRect();
//        drawRoundRect();
//         drawOval();
//        drawArc();
//        drawPath();
//        drawRectPath(canvas);
//        drawTextOnPath();
        drawBitmap();
    }
    /*----------------------------基本图形绘制----------------------------*/

    /**
     * 直线
     */
    private void drawLine() {
        mCanvas.drawLine(100, 100, 200, 200, mPaint);
//        mHandler.sendEmptyMessageDelayed(drawLines,delayDrawTime);
//         mHandler.postDelayed(() -> {
//            postInvalidate();
//            drawLines(canvas);
//        }, delayDrawTime);
    }

    /**
     * 多条直线
     */
    private void drawLines() {
        float[] pts = {10, 10, 100, 100, 200, 200, 400, 400};
        mCanvas.drawLines(pts, mPaint);
    }

    /**
     * 点
     */
    private void drawPoint() {
        mCanvas.drawPoint(100, 200, mPaint);
    }
    //    参数：
//    float[] pts:点的合集，与上面直线一直，样式为｛x1,y1,x2,y2,x3,y3,……｝
//    int offset:集合中跳过的数值个数，注意不是点的个数！一个点是两个数值；
//    count:参与绘制的数值的个数，指pts[]里人数值个数，而不是点的个数，因为一个点是两个数值
//————————————————
//    版权声明：本文为CSDN博主「启舰」的原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接及本声明。
//    原文链接：https://blog.csdn.net/harvic880925/article/details/38875149

    /**
     * 多点
     */
    private void drawPoints() {
        float[] pts = {10, 10, 100, 100, 200, 200, 400, 400};
        mCanvas.drawPoints(pts, 2, 4, mPaint);
    }


    /**
     * 矩形
     */
    private void drawRect() {
        /*第一个矩形*/
        mPaint.setColor(ResUtils.getColor(R.color.gray));
        mCanvas.drawRect(10, 10, 100, 100, mPaint);
        /*第二个矩形*/
        Rect rect = new Rect(120, 10, 210, 100);
        mPaint.setColor(ResUtils.getColor(R.color.Blue));
        mCanvas.drawRect(rect, mPaint);
        /*第三个矩形*/
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(ResUtils.getColor(R.color.Green));

        RectF rectF = new RectF(230, 10, 320, 100);
        mCanvas.drawRect(rectF, mPaint);
    }

    /**
     * 圆角矩形
     */
    private void drawRoundRect() {
        RectF rectF = new RectF(100, 10, 300, 100);
        mCanvas.drawRoundRect(rectF, 20, 50, mPaint);

    }

    /**
     * 圆
     */
    private void drawCircle() {
//        调用父View的onDraw函数，因为View这个类帮我们实现了一些
        // 基本的而绘制功能，比如绘制背景颜色、背景图片等
        int r = getMeasuredWidth() / 4; //也可以是getMeasuredHeight()/2,本例中我们已经将宽高设置相等了
        //圆心的横坐标为当前的View的左边起始位置+半径
        int centerX = getLeft() + r;
        //圆心的纵坐标为当前的View的顶部起始位置+半径
        int centerY = getTop() + r;
//        开始绘制
        ToastUtil.showTest("getLeft=" + getLeft() + ",getTop" + getTop());
        mCanvas.drawCircle(centerX, centerY, r, mPaint);
    }

    /**
     * 椭圆
     */

    private void drawOval() {
//        mPaint.setStyle(Paint.Style.FILL);
        RectF rectF = new RectF(100, 10, 300, 100);
        mCanvas.drawOval(rectF, mPaint);
        Logger.d("==centerX==" + rectF.centerX() + ",centerY" + rectF.centerY());
        Logger.d("==height==" + rectF.height() + ",width" + rectF.width());

    }

    /**
     * 弧   是椭圆的一部分，而椭圆是根据矩形来生成的，所以弧当然也是根据矩形来生成的
     */
    private void drawArc() {
        RectF rectF = new RectF(100, 10, 300, 100);
        mCanvas.drawArc(rectF, 0, 90, true, mPaint);
        RectF rect2 = new RectF(400, 10, 600, 100);
        mCanvas.drawArc(rect2, 0, 90, false, mPaint);
        /*画这个只是为了看弧当然也是根据矩形来生成，*/
        mCanvas.drawRect(rectF, mPaint);
        mCanvas.drawRect(rect2, mPaint);
    }
    /*----------------------------路径及文字 ----------------------------*/

    /**
     * 直线路径
     */
    private void drawPath() {
        Path path = new Path();
        path.moveTo(10, 10); //设定起始点
        path.lineTo(10, 100);//第一条直线的终点，也是第二条直线的起点
        path.lineTo(300, 100);//画第二条直线
        path.lineTo(500, 100);//第三条直线
        path.close();
        mCanvas.drawPath(path, mPaint);
    }

    /**
     * 矩形路径
     */
    private void drawRectPath(Canvas canvas) {
        //第一个逆向生成
        Path ccwRectPath = new Path();
        RectF rectF1 = new RectF(50, 50, 250, 250);
        ccwRectPath.addRect(rectF1, Path.Direction.CCW);
        //第二个顺向生成
        Path cwRectPath = new Path();
        RectF rectF2 = new RectF(300, 50, 500, 250);
        cwRectPath.addRect(rectF2, Path.Direction.CW);
        //先画出这两个路径
        canvas.drawPath(ccwRectPath, mPaint);
        canvas.drawPath(cwRectPath, mPaint);
    }

    /**
     * 在路径上画文字
     */
    private void drawTextOnPath() {
        //第一个逆向生成
        Path ccwRectPath = new Path();
        RectF rectF1 = new RectF(50, 50, 250, 250);
        ccwRectPath.addRect(rectF1, Path.Direction.CCW);
        //第二个顺向生成
        Path cwRectPath = new Path();
        RectF rectF2 = new RectF(300, 50, 500, 250);
        cwRectPath.addRect(rectF2, Path.Direction.CW);
        //先画出这两个路径
        mCanvas.drawPath(ccwRectPath, mPaint);
        mCanvas.drawPath(cwRectPath, mPaint);
        String text = "风萧萧兮易水寒，壮士一去兮不复返";
//        mPaint.setColor(Color.WHITE);
        mPaint.setTextSize(35);
        mCanvas.drawTextOnPath(text, ccwRectPath, 0, 18, mPaint);
        mCanvas.drawTextOnPath(text, cwRectPath, 0, 18, mPaint);
    }

    /**
     * 圆角矩形路径
     * float[] radii：必须传入8个数值，分四组，分别对应每个角所使用的椭圆的横轴半径和纵轴半径，
     * 如｛x1,y1,x2,y2,x3,y3,x4,y4｝
     */
    private void drawRoundRectx() {
        Path path = new Path();
        RectF rectF1 = new RectF(50, 50, 250, 250);
        path.addRoundRect(rectF1, 10, 15, Path.Direction.CCW);
        RectF rectF2 = new RectF(300, 50, 500, 250);
        float radii[] = {10, 15, 20, 25, 30, 35, 40, 45};
        path.addRoundRect(rectF2, radii, Path.Direction.CCW);
        mCanvas.drawPath(path, mPaint);
    }

    public float bitmapX;
    public float bitmapY;
    private void drawBitmap() {
        Paint paint = new Paint();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round);
//        bitmapX = bitmap.getWidth();
//        bitmapY = bitmap.getHeightz();
        int offsetX = bitmap.getWidth() / 2;
        int offsetY = bitmap.getWidth() / 2;
        mCanvas.drawBitmap(bitmap, bitmapX-offsetX, bitmapY-offsetY, paint);
        if (!bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }

    private void testMethod() {
//        DateUtils.formatDateTime()
//        setForegroundGravity();
//        setTextAlignment();
//        setVisibility(FOCUS_DOWN);
//        setpivotX();
//        setPadding();
//        setPaddingRelative();
//        setRotation();
//        setScrollX();
    }

//    private int delayDrawTime = 1000;
//    private Handler mHandler;
//    private static final int drawLine = 0x001;
//    private static final int drawLines = 0x002;
//    private static final int drawPoint = 0x003;

//    @SuppressLint("HandlerLeak")
//    private void initHandler() {
//        mHandler = new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
////                invalidate();
////                postInvalidate();
//                switch (msg.what) {
////                    case flag_drawLine:
////                        drawLine(mCanvas);
////                        break;
//                    case drawLines:
//                        ToastUtil.showTest("=drawLines==");
//                        drawLines(mCanvas);
//                        break;
//                    case drawPoint:
//                        ToastUtil.showTest("=drawPoint==");
//                        drawPoint(mCanvas);
//                        break;
//                }
//            }
//        };
//    }

    //    private void setDelayTime() {
//        try {
//
//
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        new Thread(){
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(delayDrawTime);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
//    }
    private void RunTimer() {
        boolean result = false;
        int count = 0;
        while (!result) {
            try {
                Thread.sleep(500);
                count++;
                Logger.d("=====执行=" + count);
                if (count == 4) {
                    result = true;
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
